import React, { Suspense } from "react";
import { Routes, Route } from "react-router-dom";
import { Spin } from "antd";
import { useAuth } from "../contexts/AuthContext";
import AdminLayout from "./AdminLayout";
import TeacherLayout from "./TeacherLayout";
import StudentLayout from "./StudentLayout";
import MessageCenter from "../pages/Message/MessageCenter";
import TaskQueue from "../pages/Task/TaskQueue";
import NotificationCenter from "../pages/Notification/NotificationCenter";

// 创建一个包装器来渲染具体的布局
const LayoutWrapper: React.FC = () => {
  const { state } = useAuth();

  // 如果用户信息还在加载中
  if (state.loading || !state.user) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100vh",
        }}
      >
        <Spin size="large" tip="加载用户信息..." />
      </div>
    );
  }

  // 根据用户类型选择对应的布局
  switch (state.user.type) {
    case "admin":
      return <AdminLayout />;
    case "teacher":
      return <TeacherLayout />;
    case "student":
      return <StudentLayout />;
    default:
      // 默认使用学生布局
      return <StudentLayout />;
  }
};

const MainLayout: React.FC = () => {
  return (
    <Suspense
      fallback={
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "400px",
          }}
        >
          <Spin size="large" tip="页面加载中..." />
        </div>
      }
    >
      <LayoutWrapper />
      <Routes>
        <Route
          path="/dashboard"
          element={
            <div style={{ padding: "24px" }}>
              <h1>仪表板</h1>
              <p>欢迎使用XHT教学平台！</p>
            </div>
          }
        />
        <Route path="/messages" element={<MessageCenter />} />
        <Route path="/tasks" element={<TaskQueue />} />
        <Route path="/notifications" element={<NotificationCenter />} />
        <Route
          path="/settings"
          element={
            <div style={{ padding: "24px" }}>
              <h1>设置</h1>
              <p>系统设置页面</p>
            </div>
          }
        />

        {/* 404 页面 */}
        <Route
          path="*"
          element={
            <div
              style={{
                textAlign: "center",
                padding: "50px",
                height: "400px",
                display: "flex",
                flexDirection: "column",
                justifyContent: "center",
                alignItems: "center",
              }}
            >
              <h2>404 - 页面未找到</h2>
              <p>您访问的页面不存在</p>
            </div>
          }
        />
      </Routes>
    </Suspense>
  );
};

export default MainLayout;
